#pragma once

#include <cctype>
#include <cstring>
#include <string>
#include <vector>

/**
 * @brief 截取字符串
 *
 * @param begin 原始字符串开始地址
 * @param end_str 要查找的结束字符串
 * @return std::string
 */
inline std::string split_of_end_string(const char *begin, const char *end_str, bool contain_end = false)
{
    std::string message;
    char       *end = std::strstr((char *)begin, end_str);
    if (end) {
        int length = end - begin;
        if (contain_end)
            length += strlen(end_str);
        message.resize(length);
        memcpy((void *)message.data(), begin, length);
    }
    return message;
}

/**
 * @brief 获取分隔符长度
 *
 * @param begin
 * @param size
 * @param separator
 * @return int
 */
inline int find_sep_length(const char *begin, int size, const char *separator)
{
    int length = 0;
    for (int i = 0; i < size; i++) {
        bool found = false;
        for (int k = 0; k < strlen(separator); k++) {
            if (begin[i] == separator[k]) {
                found = true;
                break;
            }
        }

        if (!found)
            break;
    }
    return length;
}

/**
 * @brief 字符串分隔
 *
 * @param msg
 * @param separator
 * @return std::vector<std::string>
 */
inline std::vector<std::string> str_split(const std::string &msg, std::string separator)
{
    std::vector<std::string> vecStrings;

    // start 起始位置, pos 分隔符位置
    int start = 0, pos = 0;
    while ((pos = msg.find(separator, start)) != std::string::npos) {
        if (start != pos)
            vecStrings.push_back(msg.substr(start, pos - start));
        start = pos + separator.length();
    }
    if (start != msg.length())
        vecStrings.push_back(msg.substr(start));
    return vecStrings;
}

inline void lower_case(std::string &str)
{
    for (auto &c : str) {
        c = std::tolower(static_cast<unsigned char>(c));
    }
}

inline std::string str_trim(const std::string &msg, const char ch)
{
    std::string message = msg;
    while (message.length() > 0) {
        if (message[0] != ch) {
            break;
        }
        message.erase(0, 1);
    }

    while (message.length() > 0) {
        if (message[message.length() - 1] != ch)
            break;
        message.erase(message.length() - 1, message.length());
    }
    return message;
}